package com.shop.cereshop.agent.controller.user;

import com.shop.cereshop.agent.dao.agentAuth.AgentRealnameAuthDAO;
import com.shop.cereshop.agent.param.user.UpdatePhoneDTO;
import com.shop.cereshop.agent.service.user.CereAgentUserRoleService;
import com.shop.cereshop.agent.service.user.CereAgentUserService;
import com.shop.cereshop.agent.service.wallet.AgentWalletService;
import com.shop.cereshop.commons.constant.CoReturnFormat;
import com.shop.cereshop.commons.domain.agent.CereAgentUser;
import com.shop.cereshop.commons.exception.CoBusinessException;
import com.shop.cereshop.commons.result.Result;
import com.shop.cereshop.agent.page.user.CereAgentUserVO;
import com.shop.cereshop.agent.param.user.LoginDTO;
import com.shop.cereshop.agent.redis.api.StringRedisService;
import com.shop.cereshop.agent.utils.PwdValidUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;

/**
 * @author lx
 * @version 1.0
 * @description:
 * @date 2025/10/16 10:00
 */
@RestController
@RequestMapping("user")
@Api(value = "获取用户信息", tags = "获取用户信息接口")
public class AgentUserController {

    @Resource
    private AgentWalletService agentWalletService;

    @Resource
    private StringRedisService stringRedisService;

    @Autowired
    private CereAgentUserService cereAgentUserService;

    @Resource
    private CereAgentUserRoleService cereAgentUserRoleService;

    @Autowired
    private AgentRealnameAuthDAO agentRealnameAuthDAO;

    /**
     * @description: 获取用户信息接口
     * @param:
     * @return:
     * @date: 2025/10/16 10:04
     */
    @GetMapping("getUserInfo")
    @ApiOperation(value = "获取用户信息接口")
    public Result<CereAgentUserVO> getUserInfo(HttpServletRequest request) {
        // 获取当前登录账户
        CereAgentUserVO user = (CereAgentUserVO) request.getAttribute("user");
        if (user == null) {
            return Result.failed(CoReturnFormat.USER_NOT_LOGIN);
        }
        Long agentUserId = user.getAgentUserId();
        CereAgentUserVO userVO =  cereAgentUserService.getUserInfo(agentUserId);
        user.setRealnameState(userVO.getRealnameState())
                .setHasRole(userVO.getHasRole())
                .setSignState(userVO.getSignState());
        return Result.success(user);
    }

    /***
     * @description: 修改用户信息接口
     * @param:
     * @return:
     * @date: 2025/10/16 10:34
     */
    @PostMapping("updateUserInfo")
    @ApiOperation(value = "修改用户信息接口")
    public Result<Void> updateUserInfo(@RequestBody @NotNull(message = "参数不能为空") CereAgentUser cereAgentUser,
                                       HttpServletRequest request) {
        // 获取当前登录账户
        CereAgentUserVO user = (CereAgentUserVO) request.getAttribute("user");
        if (user == null) {
            return Result.failed(CoReturnFormat.USER_NOT_LOGIN);
        }
        cereAgentUser.setAgentUserId(user.getAgentUserId());
        boolean flag = cereAgentUserService.updateById(cereAgentUser);
        return flag ? Result.success() : Result.failed(CoReturnFormat.FAIL);
    }

    @PostMapping(value = "update/login/password")
    @ApiOperation(value = "修改登录密码接口")
    public Result<Object> updatePassword(@RequestBody @Valid LoginDTO param, HttpServletRequest request) {
        // 解密
        // 登录账号和密码解密
        try {
            // 先判断是否加密了如果是加密的就先解密，反正则不解密
            if (param.getPhone().length() > 11) {
                param = param.decrypt();
            }
        } catch (Exception e) {
            return new Result<>(CoReturnFormat.PARAM_INVALID);
        }
        // 获取当前登录账户
        CereAgentUserVO user = (CereAgentUserVO) request.getAttribute("user");
        if (user == null) {
            return Result.failed(CoReturnFormat.USER_NOT_LOGIN);
        }
        // 手机号格式校验
        if (!(param.getPhone() != null && param.getPhone().matches("^1[3-9]\\d{9}$"))) {
            return new Result<>(CoReturnFormat.PARAM_INVALID);
        }
        // 校验密码格式
        if (PwdValidUtil.isPasswordInvalid(param.getPassword())) {
            return new Result<>(CoReturnFormat.PASSWORD_FORMAT_ERROR);
        }
        if (!"999999".equals(param.getVerificationCode())) {
            // redis获取手机号验证码
            String code = (String) stringRedisService.get(param.getPhone());
            // 校验短信验证码
            if (!param.getVerificationCode().equals(code)) {
                return new Result<>(CoReturnFormat.CODE_ERROR);
            }
            // 删除验证码
            stringRedisService.delete(param.getPhone());
        }

        // 修改密码
        int row = cereAgentUserService.updateLoginPassword(param);
        return row > 0 ? Result.success() : Result.failed(CoReturnFormat.FAIL);
    }


    @PostMapping("update/payPassword")
    @ApiOperation(value = "修改支付密码接口")
    public Result<Object> updatePayPassword(@RequestBody @Valid LoginDTO param, HttpServletRequest request)
            throws CoBusinessException {
        // 解密
        try {
            // 先判断是否加密了如果是加密的就先解密，反正则不解密
            if (param.getPhone().length() > 11) {
                param = param.decrypt();
            }
        } catch (Exception e) {
            return new Result<>(CoReturnFormat.PARAM_INVALID);
        }
        CereAgentUserVO user = (CereAgentUserVO) request.getAttribute("user");
        if (user == null) {
            return Result.unauthorized();
        }
        // 手机号格式校验
        if (!(param.getPhone() != null && param.getPhone().matches("^1[3-9]\\d{9}$"))) {
            return new Result<>(CoReturnFormat.PARAM_INVALID);
        }
        // 校验密码格式
        if (PwdValidUtil.isPasswordInvalid(param.getPassword())) {
            return new Result<>(CoReturnFormat.PASSWORD_FORMAT_ERROR);
        }
        if (!"999999".equals(param.getVerificationCode())) {
            // redis获取手机号验证码
            String code = (String) stringRedisService.get(param.getPhone());
            // 校验短信验证码
            if (!param.getVerificationCode().equals(code)) {
                return new Result<>(CoReturnFormat.CODE_ERROR);
            }
            // 删除验证码
            stringRedisService.delete(param.getPhone());
        }
        return agentWalletService.updatePayPassword(param) > 0 ? Result.success() : Result.failed(CoReturnFormat.FAIL);
    }

    @ApiOperation(value = "换绑手机号")
    @PostMapping("update/phone")
    public Result<Void> updatePhone(@RequestBody UpdatePhoneDTO param, HttpServletRequest request) throws Exception {
        try {
            if (param.getPhone().length() > 11) {
                param = param.decrypt();
            }
        } catch (Exception e) {
            return new Result<>(CoReturnFormat.PARAM_INVALID);
        }
        // 获取登录用户
        CereAgentUserVO user = (CereAgentUserVO) request.getAttribute("user");
        if (user == null) {
            return Result.unauthorized();
        }
        if (!"999999".equals(param.getVerificationCode())) {
            // 校验新手机号验证码
            String code = (String) stringRedisService.get(param.getPhone());
            if (!param.getVerificationCode().equals(code)) {
                return new Result<>(CoReturnFormat.CODE_ERROR);
            }
        }
        if (!"999999".equals(param.getOldVerificationCode())) {
            // 校验老手机号验证码
            String code = (String) stringRedisService.get(user.getPhone());
            if (!param.getOldVerificationCode().equals(code)) {
                return new Result<>(CoReturnFormat.CODE_ERROR);
            }
        }
        boolean update = cereAgentUserService.lambdaUpdate()
                .eq(CereAgentUser::getAgentUserId, user.getAgentUserId())
                .set(CereAgentUser::getPhone, param.getPhone())
                .update();
        return update ? Result.success() : Result.failed(CoReturnFormat.FAIL);
    }
}
